// HTTP请求工具类

interface RequestOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  headers?: Record<string, string>
  body?: any
  token?: string
}

interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
  timestamp: number
}

class RequestUtil {
  private baseURL: string
  private defaultHeaders: Record<string, string>

  constructor(baseURL: string) {
    this.baseURL = baseURL
    this.defaultHeaders = {
      'Content-Type': 'application/json',
    }
  }

  // 获取存储的token
  private getToken(): string | null {
    if (typeof window !== 'undefined') {
      return localStorage.getItem('seafood_token')
    }
    return null
  }

  // 设置token
  setToken(token: string): void {
    if (typeof window !== 'undefined') {
      localStorage.setItem('seafood_token', token)
    }
  }

  // 清除token
  clearToken(): void {
    if (typeof window !== 'undefined') {
      localStorage.removeItem('seafood_token')
      localStorage.removeItem('seafood_user')
    }
  }

  // 构建完整URL
  private buildURL(endpoint: string): string {
    return `${this.baseURL}${endpoint}`
  }

  // 构建请求头
  private buildHeaders(options: RequestOptions): Record<string, string> {
    const headers = { ...this.defaultHeaders, ...options.headers }
    
    const token = options.token || this.getToken()
    if (token) {
      headers.Authorization = `Bearer ${token}`
    }
    
    return headers
  }

  // 处理响应
  private async handleResponse<T>(response: Response): Promise<ApiResponse<T>> {
    const contentType = response.headers.get('content-type')
    
    let data: any
    if (contentType && contentType.includes('application/json')) {
      data = await response.json()
    } else {
      data = await response.text()
    }

    if (!response.ok) {
      // 处理HTTP错误
      if (response.status === 401) {
        this.clearToken()
        if (typeof window !== 'undefined') {
          window.location.href = '/login'
        }
      }
      
      throw new Error(data.message || `HTTP Error: ${response.status}`)
    }

    return data
  }

  // 通用请求方法
  async request<T = any>(endpoint: string, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const url = this.buildURL(endpoint)
    const headers = this.buildHeaders(options)
    
    const config: RequestInit = {
      method: options.method || 'GET',
      headers,
    }

    // 处理请求体
    if (options.body && options.method !== 'GET') {
      if (headers['Content-Type'] === 'application/json') {
        config.body = JSON.stringify(options.body)
      } else {
        config.body = options.body
      }
    }

    try {
      const response = await fetch(url, config)
      return await this.handleResponse<T>(response)
    } catch (error) {
      console.error('Request failed:', error)
      throw error
    }
  }

  // GET请求
  async get<T = any>(endpoint: string, options: Omit<RequestOptions, 'method' | 'body'> = {}): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { ...options, method: 'GET' })
  }

  // POST请求
  async post<T = any>(endpoint: string, body?: any, options: Omit<RequestOptions, 'method' | 'body'> = {}): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { ...options, method: 'POST', body })
  }

  // PUT请求
  async put<T = any>(endpoint: string, body?: any, options: Omit<RequestOptions, 'method' | 'body'> = {}): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { ...options, method: 'PUT', body })
  }

  // DELETE请求
  async delete<T = any>(endpoint: string, options: Omit<RequestOptions, 'method' | 'body'> = {}): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { ...options, method: 'DELETE' })
  }

  // 文件上传
  async upload<T = any>(endpoint: string, file: File, options: Omit<RequestOptions, 'method' | 'body'> = {}): Promise<ApiResponse<T>> {
    const formData = new FormData()
    formData.append('file', file)
    
    const headers = { ...options.headers }
    delete headers['Content-Type'] // 让浏览器自动设置Content-Type
    
    return this.request<T>(endpoint, {
      ...options,
      method: 'POST',
      headers,
      body: formData,
    })
  }
}

// 创建请求实例
const API_BASE_URL = typeof window !== 'undefined' 
  ? (window as any).env?.API_BASE_URL || process.env.API_BASE_URL || 'http://localhost:8080/api'
  : process.env.API_BASE_URL || 'http://localhost:8080/api';

export const request = new RequestUtil(API_BASE_URL)

// 导出类型
export type { RequestOptions, ApiResponse }